<template>
  <div>
    <div class="search">
      <el-card>
        <el-form :inline="true" :model="searchData" class="demo-form-inline">
          <el-form-item label="角色ID">
            <el-input v-model="searchData.user" placeholder="角色ID" clearable />
          </el-form-item>

          <el-form-item label="角色名称">
            <el-input v-model="searchData.region" placeholder="角色名称" clearable />
          </el-form-item>
          <el-form-item label="角色编码">
            <el-input v-model="searchData.date" placeholder="角色编码" clearable />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="onSearchSubmit">搜索</el-button>
          </el-form-item>

        </el-form>
      </el-card>
    </div>

    submitForm

    <div class="mytable">
      <el-card class="gongju">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-button type="primary" @click="addItemHandler()"> 添加 </el-button>
          </el-col>
        </el-row>
      </el-card>
      <el-card>
        <el-table :data="tableData" style="width: 100%">
          <el-table-column fixed prop="id" label="角色ID" width="150" />
          <el-table-column prop="name" label="角色名称" width="300" />
          <el-table-column prop="code" label="角色编码" width="120" />
          <el-table-column prop="status" label="角色状态" width="120" />
          <el-table-column prop="sort" label="排序" width="120" />
          <el-table-column prop="updateTime" label="更新时间" width="220" />
          <el-table-column fixed="right" label="操作" min-width="120">
            <template #default="{ row }">
              <el-button link type="primary" size="small" @click="editItemHandler(row)">
                修改
              </el-button>
              <el-button link type="primary" size="small" @click="delItemHandler(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
    <div class="mypage">
      <el-pagination background layout="prev, pager, next" :total="pageParams.total" @change="pageChangeHandler" />
    </div>

    <!-- 弹框 -->

    <el-dialog v-model="dialogFormVisible" title="Shipping address" width="800">
      <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto"
        class="demo-ruleForm" :size="formSize" status-icon>

        <el-form-item label="角色ID" prop="id">
          <el-input v-model="ruleForm.id" />
        </el-form-item>

        <el-form-item label="角色名称" prop="name">
          <el-input v-model="ruleForm.name" />
        </el-form-item>

        <el-form-item label="角色编码" prop="code">
          <el-input v-model="ruleForm.code" />
        </el-form-item>

        <el-form-item label="角色状态" prop="delivery">
          <el-switch v-model="ruleForm.status" inline-prompt active-text="启用" inactive-text="禁用" :active-value="1"
            :inactive-value="0" />
        </el-form-item>


        <el-form-item>
          <el-button type="primary" :disabled="isSBtnDisable" :loading="isSBtnLoding" @click="submitForm(ruleFormRef)">
            Create
          </el-button>
          <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
        </el-form-item>

      </el-form>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { type RolesType, requestGetRolesPage, addRole, editRole, delRole } from '@/service/study6/demo2'
import { ElMessage, ElMessageBox, type ComponentSize, type FormInstance, type FormRules } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'


// 初始化
const initAction = () => {
  onSearchSubmit()
  console.log(initAction, 'initAction');
}
const onSearchSubmit = async () => {
  // 更新分页参数，通常搜索会从第一页开始
  pageParams.value.pageNum = 1;
  console.log(onSearchSubmit);

  // 调用请求分页数据的方法，并传递搜索参数
  const resRoles = await requestGetRolesPage({
    pageNum: pageParams.value.pageNum,
    pageSize: pageParams.value.pageSize,
    user: searchData.user, // 角色ID
    region: searchData.region, // 角色名称
    date: searchData.date // 角色编码
  });
  console.log(resRoles);
  if (resRoles && resRoles.code === '2000') {
    // 更新表格数据
    tableData.value = resRoles.data.list;
    // 更新总数据量
    pageParams.value.total = resRoles.data.total;
  } else {
    // 处理错误情况，例如弹出提示信息
    ElMessage.error('搜索数据失败');
  }
};

const tableData = ref<RolesType[]>()
const pageParams = ref({
  pageNum: 1, //当前页
  pageSize: 20, //每页数量
  total: 0
})

// 是否显示 Dialog
const dialogFormVisible = ref(false)
const isSBtnLoding = ref(false)
const isSBtnDisable = ref(false)
const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<RolesType>({
  code: '',
  createTime: '',
  name: '',
  sort: 1,
  status: 1
})
const ruleFormInfo = ref<{ type: 'add' | 'edit'; title: string }>({
  type: 'add',
  title: '添加数据'
})

const locationOptions = ['Home', 'Company', 'School']

const rules = reactive<FormRules<RolesType>>({
  id: [{ required: true, message: '不可以为空', trigger: 'blur' }],
  name: [{ required: true, message: '不可以为空', trigger: 'blur' }],
  code: [{ required: true, message: '不可以为空', trigger: 'blur' }],
  status: [{ required: true, message: '不可以为空', trigger: 'blur' }]
})

const submitForm = async (formEl: FormInstance | undefined) => {
  isSBtnLoding.value = true
  isSBtnDisable.value = true

  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      ruleForm.value.id = Number(ruleForm.value.id)

      // 添加
      if (ruleFormInfo.value.type === 'add') {
        // http请求
        const res = await addRole(ruleForm.value)
        if (res.code !== '2000') {
          ElMessage.error('数据添加失败')
          return
        }
        ElMessage.success('数据添加成功')
      }
      // 修改
      if (ruleFormInfo.value.type === 'edit') {
        // http请求
        const res = await editRole(ruleForm.value.id, ruleForm.value)
        if (res.code !== '2000') {
          ElMessage.error('数据修改失败')
          return
        }
        ElMessage.success('数据修改成功')
      }
      isSBtnLoding.value = false
      isSBtnDisable.value = false
      // 关闭模态框
      dialogFormVisible.value = false
      getPageData()
      // 重置表单
      formEl.resetFields()
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const searchData = reactive({
  user: '',
  region: '',
  date: ''
})

// const onSearchSubmit = () => {
//   console.log('submit!')
// }

// /**
//  * 获取分页数据
//  */
const getPageData = async () => {
  const resRoles = await requestGetRolesPage({
    pageNum: pageParams.value.pageNum,
    pageSize: pageParams.value.pageSize
  })
  console.log(resRoles, 'resRoles')
  tableData.value = resRoles.data.list
  pageParams.value.total = resRoles.data.total
}

/**
 * 添加数据
 */
const addItemHandler = () => {
  ruleFormInfo.value = {
    type: 'add',
    title: '添加角色'
  }
  // 清空验证
  ruleFormRef.value?.clearValidate()
  // 重置表单
  ruleFormRef.value?.resetFields()
  dialogFormVisible.value = true
}

/**
 * 修改
 */
const editItemHandler = (row: RolesType) => {
  ruleFormInfo.value = {
    type: 'edit',
    title: '修改角色'
  }
  console.log(row, 'rowrowrow')
  ruleForm.value = row
  dialogFormVisible.value = true
}

/**
 * 删除数据
 */
const delItemHandler = (row: RolesType) => {
  ElMessageBox.confirm('确定要删除吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 发起删除请求
      const res = await delRole(JSON.parse(JSON.stringify(row.id)))
      if (res.code !== '2000') {
        throw new Error(res.msg)
      }
      // await delRole(row.id);
      ElMessage({
        type: 'success',
        message: '删除成功'
      })
      // 重新获取表格数据
      getPageData()

    } catch (error: any) {
      ElMessage({
        type: 'error',
        message: error.message
      });

    }
  })
    .catch(() => {
      ElMessage.info({
        type: 'info',
        message:'取消删除'
      });

    });
};

onMounted(() => {
  getPageData()
})

// 分页时间
const pageChangeHandler = (currentPage: number, pageSize: number) => {
  pageParams.value.pageNum = currentPage
  pageParams.value.pageSize = pageSize
  getPageData()
}
</script>

<style lang="scss" scoped>
.search {
  // border: 1px solid var(--el-border-color);
}

.mytable {
  // margin: 10px 0;
  // border: 1px solid var(--el-border-color);
}

.mypage {
  margin: 10px 0;
  // border: 1px solid var(--el-border-color);
}

.gongju {
  margin: 10px 0;
}
</style>
